﻿using System;
using ECBS_Backend.dao;
using ECBS_Backend.model;
using System.Linq;
using ECBS_Backend.utils;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace ECBS_Backend.service
{
    public class AdminService
    {
        private readonly ECBSContext context;

        private HttpUtils httpUtils;

        public AdminService(ECBSContext context, HttpUtils httpUtils)
        {
            this.context = context;
            this.httpUtils = httpUtils;
        }

        /// <summary>
        /// 管理员账号登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Admin AdminLogin(string userName, string password)
        {
            var admin = context.Admins.SingleOrDefault(s => s.UserName == userName);

            if(admin == null){
                throw new Exception("账号未注册！");
            }

            if(admin.Password != password){
                throw new Exception("密码错误！");
            }

            return admin;
        }

        /// <summary>
        /// 学校账号登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public School SchoolLogin(string userName, string password)
        {
            var school = context.Schools.SingleOrDefault(s => s.UserName == userName);

            if(school == null){
                throw new Exception("账号未注册！");
            }

            if(school.Password != password){
                throw new Exception("密码错误！");
            }

            if(!school.isRecognized)
            {
                throw new Exception("您还未被认证为权威证书发行者，请联系超级管理员！");
            }

            return school;
        }

        /// <summary>
        /// 企业账号登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public Enterprise EnterpriseLogin(string userName, string password)
        {
            var enterprise = context.Enterprises.SingleOrDefault(e => e.UserName == userName);

            if(enterprise == null){
                throw new Exception("账号未注册！");
            }

            if(enterprise.Password != password){
                throw new Exception("密码错误！");
            }

            return enterprise;
        }

        /// <summary>
        /// 超级管理员增加学校,注册为权威证书发行者
        /// </summary>
        /// <param name="school"></param>
        /// <returns></returns>
        public School AddandVerifySchool(School school, string adminWeID)
        {
            // 验证数据库中是否已经存在该学校
            var sch = context.Schools.SingleOrDefault(s => s.UserName == school.UserName);
            if(sch != null){
                throw new Exception("学校账号重复！");
            }

            sch = context.Schools.SingleOrDefault(s => s.Name == school.Name);
            if(sch != null){
                throw new Exception("学校名称重复！");
            }

            // 获取WeID并赋值给School.WeID
            school.WeID = httpUtils.createWeId();
            school.isRecognized = false;

            // 注册为权威证书发行者
            httpUtils.registerAuthorityIssuer(adminWeID, school.WeID, school.Name);

            // 添加进入数据库
            _ = context.Schools.Add(school);

            // 验证是否操作数据库功
            if(context.SaveChanges() == 0){
                throw new Exception("添加失败！");
            }

            return school;
        }

        /// <summary>
        /// 将学校认证为权威证书发行者
        /// </summary>
        /// <param name="schoolWeID"></param>
        /// <returns></returns>
        public bool RecognizeSchool(string schoolWeID)
        {
            School school = context.Schools.SingleOrDefault(s => s.WeID == schoolWeID);
            if(school == null)
            {
                throw new Exception("该学校不存在！");
            }
            school.isRecognized = httpUtils.recognizeAuthorityIssuer(schoolWeID);
            if(context.SaveChanges() < 1)
            {
                throw new Exception("认证状态修改失败！");
            }
            return true;
        }

        /// <summary>
        /// 撤销学校权威证书发行者
        /// </summary>
        /// <param name="schoolWeID"></param>
        /// <returns></returns>
        public bool DeRecognizeSchool(string schoolWeID)
        {
            School school = context.Schools.SingleOrDefault(s => s.WeID == schoolWeID);
            if(school == null)
            {
                throw new Exception("该学校不存在！");
            }
            httpUtils.deRecognizeAuthorityIssuer(schoolWeID);
            school.isRecognized = false;
            if (context.SaveChanges() < 1)
            {
                throw new Exception("认证状态修改失败！");
            }
            return true;
        }

        /// <summary>
        /// 超级管理员增加企业
        /// </summary>
        /// <param name="enterprise"></param>
        /// <returns></returns>
        public Enterprise AddEnterprise(Enterprise enterprise)
        {
            // 验证数据库中是否已经存在该公司
            var sch = context.Enterprises.SingleOrDefault(s => s.UserName == enterprise.UserName);
            if(sch != null){
                throw new Exception("公司账号重复！");
            }

            sch = context.Enterprises.SingleOrDefault(s => s.Name == enterprise.Name);
            if(sch != null){
                throw new Exception("公司名称重复！");
            }

            // 获取WeID并赋值给School.WeID
            enterprise.WeID = httpUtils.createWeId();


            // 添加进入数据库
            context.Enterprises.Add(enterprise);

            // 验证是否操作数据库功
            if(context.SaveChanges() == 0){
                throw new Exception("添加失败！");
            }

            return enterprise;
        }

        /// <summary>
        /// 超级管理员查看学校
        /// </summary>
        /// <returns></returns>
        public dynamic DisplaySchool(string keyword){
            try
            {
                if (keyword == null || keyword == "")
                {
                    return context.Schools.Select((s) => new { WeID = s.WeID, Name = s.Name, IsRecognized = s.isRecognized }).ToList();
                }
                List<School> list = context.Schools.Where((e) => e.Name.Contains(keyword)).ToList();
                return list.Select((s) => new { WeID = s.WeID, Name = s.Name, IsRecognized = s.isRecognized }).ToList();
            }
            catch (Exception e)
            {
                 throw new Exception("获取列表出错！");
            }
        }

        /// <summary>
        /// 超级管理员查看企业
        /// </summary>
        /// <returns></returns>
        public dynamic DisplayEnterprise(string keyword){
            try
            {
                if(keyword == null || keyword == "")
                {
                    return context.Enterprises.Select((e) => new { WeID = e.WeID, Name = e.Name }).ToList();
                }
                List<Enterprise> list = context.Enterprises.Where((e) => e.Name.Contains(keyword)).ToList();
                return list.Select((e) => new { WeID = e.WeID, Name = e.Name }).ToList();
            }
            catch (Exception e)
            {
                 throw new Exception("获取列表出错！");
            }
        }

        /// <summary>
        /// 删除企业
        /// </summary>
        /// <param name="WeID"></param>
        /// <returns></returns>
        public Enterprise DeleteEnterprise(string WeID)
        {
            var enterprise = context.Enterprises.SingleOrDefault(e => e.WeID == WeID);
            if (enterprise == null)
            {
                throw new Exception("未找到该公司账号");
            }

            context.Enterprises.Remove(enterprise);

            if(context.SaveChanges() < 1)
            {
                throw new Exception("删除公司账号失败");
            }

            return enterprise;
        }
    }
}
